package com.hzdaba.aiapi.handlerInterceptor;

import com.hzdaba.aiapi.service.AiWitheListService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 校验白名单
 *
 * @author 刘逸晖
 */
@Component
public class CheckWhiteListHandlerInterceptor implements HandlerInterceptor {

    /**
     * 访问白名单数据
     */
    @Autowired
    private AiWitheListService aiWitheListService;

    /**
     * 缓存用户是否在白名单中的 key
     */
    @Value("${aiapi.aiwithelist.cache.keys.prefix}")
    private String keyOfWitheList;

    /**
     * 请求中存放错误信息的 key
     */
    @Value("${aiapi.request.attribute.error.key}")
    private String keyOfError;

    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CheckWhiteListHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求中取出用户 id ，这是在校验 token 时放进去的
        Integer idOfCustomer = (Integer) request.getAttribute("idOfCustomer");

        if (idOfCustomer == null) {//未登录
            response.setStatus(403);
            request.setAttribute(this.keyOfError, "抱歉，该接口要登录后才可访问");
            request.getRequestDispatcher("/error/error").forward(request, response);

//            CheckWhiteListHandlerInterceptor.logger.info("客户端未登录，无法检查白名单，拒绝访问");
            return false;
        }

        //查询当前 ip 是否可以在当前时间以当前用户的身份登录

        //先从 session 中查
        HttpSession session = request.getSession();
        Boolean allowable = (Boolean) session.getAttribute(this.keyOfWitheList);

        if (allowable == null) {//缓存中没有
            Integer count = this.aiWitheListService.countEffectiveAiWitheList(request.getRemoteAddr(), idOfCustomer, new Date().getTime());
            allowable = count != null && count > 0;

            session.setAttribute(this.keyOfWitheList, allowable);
        }

        if (!allowable) {//不在白名单里面
            response.setStatus(403);
            request.setAttribute(this.keyOfError, "抱歉，您不在可访问的白名单里面。您的 ip ：" + request.getRemoteAddr());
            request.getRequestDispatcher("/error/error").forward(request, response);

//            CheckWhiteListHandlerInterceptor.logger.info("客户端不在白名单中，不与访问");
        }

        return allowable;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
